#include <QtGlobal>
#include <iostream>
#include <QJsonObject>
#include <QJsonDocument>

#include "AnGlobal.h"
#include "AnAdbServer.h"

QString adb_path;
int port;
AnAdbServer * adb_server;
QString hostname;
QString current_devices_id;
QMutex device_connect_lock;
QMutex device_close_lock;

AnSysCallback * sys_callback;
int  adb_installed;
QApplication * app;

QMutex lock_devices_check;
QMutex lock_devices_info;
QMutex lock_app_list;
QMutex lock_app_install;
QMutex lock_app_uninstall;
QMutex lock_file_list;
QMutex lock_file_import;
QMutex lock_file_export;
QMutex lock_contacts_backup;
QMutex lock_contacts_recovery;
QMutex lock_connect_build;
QMutex lock_connect_close;
QMutex lock_screencap;



void AnGlobal::globalInit()
{
#ifdef Q_OS_WIN
	adb_path = QString(".\\adb\\adb.exe");
#else
    adb_path = QString("/bin/adb");
#endif

	port = 4396;
	adb_server = new AnAdbServer();
	hostname = "localhost";
    sys_callback = new AnSysCallback;
    adb_installed = 0;
}


void AnGlobal::globalFinal()
{
    delete adb_server;
}


int AnGlobal::is_connecting()
{
    if (device_connect_lock.tryLock()) {
        device_connect_lock.unlock();
        return NO;
    }
    return YES;
}

int AnGlobal::is_request_processing(QString request_name)
{
    QMutex * lock;

    if (request_name == "devices_check") {
        lock = &lock_devices_check;
    } else if (request_name == "devices_info") {
        lock = &lock_devices_info;
    } else if (request_name == "app_list") {
        lock = &lock_app_list;
    } else if (request_name == "app_install") {
        lock = &lock_app_install;
    } else if (request_name == "app_uninstall") {
        lock = &lock_app_uninstall;
    } else if (request_name == "file_list") {
        lock = &lock_file_list;
    } else if (request_name == "file_import") {
        lock = &lock_file_import;
    } else if (request_name == "file_export") {
        lock = &lock_file_export;
    } else if (request_name == "contacts_backup") {
        lock = &lock_contacts_backup;
    } else if (request_name == "contacts_recovery") {
        lock = &lock_contacts_recovery;
    } else if (request_name == "connect_build") {
        lock = &lock_connect_build;
    } else if (request_name == "connect_close") {
        lock = &lock_connect_close;
    } else if (request_name == "screencap") {
        lock = &lock_screencap;
    } else {
        return NO;
    }

    if (lock->tryLock()) {
        lock->unlock();
        return NO;
    } else {
        return YES;
    }
}


void AnGlobal::log_show(QJsonObject json_o, QString desp)
{
    std::cout << desp.toUtf8().data() << QJsonDocument(json_o).toJson().data() << std::endl;
}
